import { createRouter, createWebHistory  } from "vue-router"

import HomePage from '../pages/HomePage.vue'
import axios from "axios"
import { ElMessage } from "element-plus"

export default createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            component: HomePage
        },
        {
            path: '/login',
            component: () => import('../pages/LoginPage.vue')
        },
        {
            path: '/register',
            component: () => import('../pages/RegisterPage.vue')
        },
        {
            path: '/home',
            redirect: '/'
        },
        {
            path: '/about',
            component: () => import('../pages/AboutPage.vue')
        },
        {
            path: '/timeline',
            component: () => import('../pages/TimelinePage.vue')
        },
        {
            path: '/author',
            component: () => import('../pages/AuthorPage.vue')
        },
        {
            path: '/passage',
            component: () => import('../pages/PassagePage.vue')
        },
        {
            path: '/anime',
            component: () => import('../pages/Animepage.vue')
        },
        {
            path: '/music',
            component: () => import('../pages/MusicPage.vue')
        },
        {
            path: '/blog/:id',
            component: () => import('../pages/BlogPage.vue')
        },
        {
            path: '/profile',
            component: () => import('../pages/ProfilePage.vue')
        },
        {
            path: '/edit',
            component: () => import('../pages/EditPage.vue'),
            beforeEnter(to, from, next) {
                axios.get('http://localhost/api/getUserInfo', {
                    headers: {
                        Authorization: 'Bearer '+sessionStorage.getItem('token')
                    }
                }).then(res => {
                    let userInfo = res.data
                    if(userInfo.authority == 'root' || userInfo.username == 'admin') {
                        next()
                    } else {
                        ElMessage.error('你没有权限查看此项！')
                        next('/home')
                    } 
                }).catch(err => {
                    ElMessage.error('你没有权限查看此项！')
                    next('/home')
                    console.log(err)
                })
            }
        }
    ]
})